const express = require('express')
const router = express.Router()

const {
    New
} = require('../models')

// 获取图片新闻
router.get('/home/getImgNews', async (req, res) => {
    // 接收分页页码和每页显示的条数
    const page = req.query.page || 1
    const pageSize = req.query.pageSize || 5
    const offset = (page - 1) * pageSize
    // 接收分类id
    const cate_id = req.query.cate_id || 0
    // 判断是否传递了cate_id
    let conditions = {
        attributes: ['id', 'img_url', 'title', 'cateId'],
        order: [
            ['view_nums', 'desc']
        ],
        offset,
        limit: pageSize
    }
    if (cate_id) {
        conditions.where = {
            cateId: cate_id
        }
    }

    const data = await New.findAll(conditions)
    return res.cc(200, 'success', data)
})
// 最新新闻
router.get('/home/getNewNews', async (req, res) => {
    // 接收分页页码和每页显示的条数
    const page = req.query.page || 1
    const pageSize = req.query.pageSize || 10
    const offset = (page - 1) * pageSize
    // 接收分类id
    const cate_id = req.query.cate_id || 0
    let conditions = {
        attributes: ['id', 'add_time', 'title'],
        order: [
            ['add_time', 'desc']
        ],
        offset,
        limit: pageSize
    }
    if (cate_id) {
        conditions.where = {
            cateId: cate_id
        }
    }
    const data = await New.findAll(conditions)
    return res.cc(200, 'success', data)
})

// 最热新闻
router.get('/home/getHotNews', async (req, res) => {
    // 接收分页页码和每页显示的条数
    const page = req.query.page || 1
    const pageSize = req.query.pageSize || 10
    const offset = (page - 1) * pageSize
    const data = await New.findAll({
        attributes: ['id', 'add_time', 'title'],
        order: [
            ['view_nums', 'desc']
        ],
        offset,
        limit: pageSize
    })
    return res.cc(200, 'success', data)
})

// 获取某条新闻的数据
router.get('/home/news/:id',async (req, res) => {
    const id = req.params.id
    const data = await New.findAll({
        where:{
            id
        },
        attributes: ['id', 'add_time', 'title','view_nums','content','author','cateId']
    })
    return res.cc(200, 'success', data)
})

// 更新新闻的访问量
router.put('/home/news/:id', async (req, res) => {
    const id = req.params.id
    const result = await New.findByPk(id)
    result.increment({view_nums:1})
    return res.cc(200, 'success')
})

module.exports = router